package com.mo.modular.auth.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.mo.common.exception.BussinessException;
import com.mo.common.exception.TvExceptionEnum;
import com.mo.config.properties.BaseInfoProperties;
import com.mo.config.properties.JwtProperties;
import com.mo.modular.auth.controller.dto.AuthResponse;
import com.mo.modular.auth.controller.dto.AuthSiteResponse;
import com.mo.modular.auth.util.JwtTokenUtil;
import com.mo.tv.service.IZlSiteService;
import com.mo.tv.service.IZlUserService;

/**
 * 请求验证的
 *
 * @author chenxiaodong
 * @Date 2017/8/24 14:22
 */
@RestController
@Api(value = "auth", description = "设备注册模块")
public class AuthController {

	private static Logger logger = Logger.getLogger(AuthController.class);
	
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IZlUserService zlUserService;
    
    @Autowired
	private IZlSiteService zlSiteService;
    
    @Autowired
    private JwtProperties jwtProperties;
    
    @Autowired
    private BaseInfoProperties baseInfoProperties;

	@ApiOperation(value = "创建令牌",notes = "用戶初始获取token值")
    @ApiImplicitParams({
        @ApiImplicitParam(name="tvid",value="tvId",required=true,paramType="form",dataType="String")
    })
    @RequestMapping(value = "${jwt.auth-path}",method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(String tvid) {
    	boolean validate = true;
    	String string = stringRedisTemplate.opsForValue().get(tvid);
    	Long siteId=null;
    	if(string==null){
    		Map<String, Object> result = zlSiteService.findZlSiteIdByTvId(tvid);
    		if(result.get("siteId")!=null){
    			siteId=(Long)(result.get("siteId"));
    			validate=zlUserService.checkAndAdd((String)result.get("stbPrefix"), tvid);
        	}else{
        		logger.info("**********此TVID无站点信息**********");
        		validate=false;
        	}
    	}else{
    		Map<String, Object> result = zlSiteService.findZlSiteIdByTvId(tvid);
    		siteId=(Long)(result.get("siteId"));
    	}
    	
        if (validate) {
            final String randomKey = jwtTokenUtil.getRandomKey();
            final String token = jwtTokenUtil.generateToken(tvid, randomKey);
            stringRedisTemplate.opsForValue().set(token, "token",jwtProperties.getExpiration(),TimeUnit.SECONDS);
            
           // return ResponseEntity.ok(new AuthResponse(token, randomKey));
            AuthSiteResponse authSiteResponse = new AuthSiteResponse(token, randomKey,siteId);
            return ResponseEntity.ok(authSiteResponse);
        } else {
            throw new BussinessException(TvExceptionEnum.AUTH_REQUEST_ERROR);
        }
    }
}
